package com.ruoyi.system.component;

import com.alibaba.fastjson.JSON;
import com.ruoyi.system.domain.Address;
import com.ruoyi.system.mapper.AddressMapper;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

@Component
public class AddressService {

    private static final Logger log = LoggerFactory.getLogger(AddressService.class);

    private static final List<Map<String, Object>> ADDRESS_LIST = new ArrayList<>();

    @Autowired
    private AddressMapper addressMapper;

    @PostConstruct
    private void init(){
        log.info("init all address start...");
        Long startTime = System.currentTimeMillis();
        CopyOnWriteArrayList<Address> addressList = addressMapper.selectAddress();

        if(addressList.isEmpty()){
            return ;
        }

        ADDRESS_LIST.addAll(this.get(addressList,0L));
        Long endTime = System.currentTimeMillis();
        log.info("init all address end, use [ {} ] millisecond", endTime - startTime);

    }

    private List<Map<String,Object>> get(List<Address> addressList, Long pid){

        List<Map<String,Object>> list = new ArrayList<>();

        for(Address address : addressList){

            if (Objects.equals(address.getPid(), pid)) {


                Map<String, Object> parent = new HashMap<>();

                parent.put("n", address.getName());

                List<Map<String, Object>> child = this.get(addressList, address.getId());

                if (CollectionUtils.isNotEmpty(child)) {
                    parent.put("s", child);
                }

                list.add(parent);
            }
        }
        return list;
    }

    public String getAddressData(){
        return JSON.toJSONString(ADDRESS_LIST);
    }

}
